<template>
	<view class="status_bar">
		<!-- 这里是状态栏 -->
	</view>
	<view class="start-Keeeping-accounts">


		<uni-nav-bar :border="false" left-icon="left" @clickLeft="goIndex" right-width="0">
			<view class="in-out">
				<uni-segmented-control :current="current" :values="items" style-type="text" active-color="#007aff"
					@clickItem="onClickItem" />
			</view>

			<view class="city" @click="selectAccountBookFn">
				<text>{{form.accountBookName}}</text>
				<uni-icons type="bottom" size="15"></uni-icons>
			</view>
			<block slot="right"></block>
		</uni-nav-bar>
		<view class="dayly">
			<view class="left">
				<uni-icons type="fire" size="40" color="#fff"></uni-icons>
				<!-- <picker @change="bindPickerChange" :value="currentPicker" :range="pickerArray">
					<text class="text-1">{{form.expenditureItem}} </text>
				</picker> -->
				<text class="text-1 ">{{form.expenditureType}}</text>
			</view>
			<text class="amount" @click="()=>changeKeyboard('expenditureAmount')">{{form.expenditureAmount}} </text>
		</view>
		<scroll-view scroll-y="true" class=" scroll-Y">
			<view class="assets-content">
				<view v-for="i in  categoryList" class="assets-content-view" @click="()=>changeSelectIcon(i)">
					<uni-icons class="select-icon" v-show="deleteFlag" :type=" i.selected?'checkbox-filled':'checkbox'"
						size="15"></uni-icons>
					<uni-icons class="icon" fontFamily="CustomFont" :size="30"
						:color="form.expenditureItemId ===i.id  ?'#559ae8' :'#333'">{{unicodeToChar(i.iconName)}}</uni-icons>
					<text>{{(i.categoryName)}}</text>
				</view>


				<view v-show="!deleteFlag" class="assets-content-view">
					<uni-icons class="icon" fontFamily="CustomFont" :size="30"
						@click="()=>goTo('customCategory')">{{ '\ue607'}}</uni-icons>
					<text>自定义</text>
				</view>

				<!--
				<view class="assets-content-view">
					<uni-icons class="icon" fontFamily="CustomFont" :size="30"
						@click="()=>goTo('customCategory')">{{ '\ue62b'}}</uni-icons>
					<text>修改</text>
				</view> -->
				<view v-show="deleteFlag" class="assets-content-view">
					<uni-icons class="icon" fontFamily="CustomFont" :size="30"
						@click="deleteCancel">{{ '\ue63f'}}</uni-icons>
					<text> 取消</text>
				</view>
				<view class="assets-content-view">
					<uni-icons class="icon" fontFamily="CustomFont" :size="30"
						@click="()=> deleteFlag ?doDeleteFn():deleteFn()">{{ '\ue63f'}}</uni-icons>
					<text>{{ deleteFlag? '确认删除' : '删除' }}</text>
				</view>

			</view>
		</scroll-view>
		<!-- 扫描 -->
		<uni-icons class="ocr" type="scan" size="35" @click="orc"></uni-icons>
		<view class="selet-section">
			<view class="selet-section-top">
				<view class="selet-section-items select-account" @click="selectAccountShow">
					<view class="item">
						<uni-icons type="wallet" size="30" color="#fff"></uni-icons>
						<text class="text-1">{{ selectedAccount  ||'选择账户'}} </text>
					</view>
					<uni-icons type="right" size="20" color="#fff" class="icon-right"></uni-icons>
				</view>
				<view class="selet-section-items">
					<uni-icons v-if="current ===0" type="list" size="30"></uni-icons>
					<text v-if="current ===0" class="text-1">核算项目 </text>
					<text v-if="current ===1">数量： </text>
					<text v-if="current ===1" @click="()=>changeKeyboard('quantity')" class="quantity">{{form.quantity}}
					</text>
				</view>
			</view>
			<view class="selet-section-bottom">
				<view class="selet-section-items  selet-time">
					<view class="item">
						<!-- <uni-icons type="fire" size="30" color="#000"></uni-icons> -->
						<uni-datetime-picker :border="true" :clear-icon="false" type="datetime"
							v-model="form.expenditureTime" @change="bindMonthDateChange2" />
						<!-- 	<picker mode="" :value="form.expenditureTime" :start="startDate" :end="endDate"
							@change="bindMonthDateChange">
							<text>{{form.expenditureTime}}</text>
						</picker> -->
					</view>
					<!-- <uni-icons type="right" size="20" color="#000" class="icon-right"></uni-icons> -->
				</view>
				<view class="selet-section-items" @click="remarkShow">
					<uni-icons type="fire" size="30" color="#000"></uni-icons>
					<text class="text-1">{{form.remarks.slice(0,4)}} </text>
				</view>
			</view>
		</view>


	</view>
	<!-- 键盘 -->
	<!-- <uni-popup ref="popUpKeyRef" type="bottom" background-color="#fff"> -->
	<pan-keyboard ref="panKeyBoardRef" class="key" @onChange="onPanKeyboardChange" @onSubmit="onSubmit"></pan-keyboard>
	<!-- </uni-popup> -->
	<!-- 选择资产账户 -->
	<uni-popup ref="popUpRef" type="bottom" background-color="#fff">
		<view class="popup-header">
			<view class="cancel" @click="selectCancel">
				取消
			</view>
			<view class="cancel">
				资产账户
			</view>
			<view class="sure" @click="selectOk">
				确定
			</view>
		</view>
		<view class="accounts">
			<!-- TODO    			<scroll-view scroll-y="true" class="scroll-Y"> -->
			<view v-for=" i  in assets" class="list-item" @click="()=> selectAccount(i)">
				<view class="list-item-content">
					<uni-icons :type="i.icon || 'wallet'" size="45"></uni-icons>
					<view class="list-item-content-view">
						<view>{{i.accountName}}</view>
					</view>
				</view>
				<view class="money">
					<text>￥{{ i.balance }}</text>
					<uni-icons class="select-icon" v-show="i.selected" type="checkbox-filled" size="25"></uni-icons>
				</view>
			</view>
		</view>
	</uni-popup>
	<!-- 备注 -->
	<uni-popup ref="popUpRemarkRef" type="bottom" background-color="#fff">
		<view class="rmark">
			<uni-easyinput type="textarea" autoHeight v-model="form.remarks" focus placeholder="请输入内容"
				@input="input"></uni-easyinput>
		</view>
	</uni-popup>

	<uni-popup ref="alertDialogRef" type="dialog">
		<uni-popup-dialog type="error" cancelText="关闭" confirmText="同意" title="提示" :content=" messageText "
			@confirm="deleteOk" @close="dialogClose"></uni-popup-dialog>
	</uni-popup>
	<selectAccountBook :accountName="form.accountBookName" ref="selectAccountBookRef"
		@selectAccountBookOk="selectAccountBookOk">
	</selectAccountBook>
</template>

<script lang="ts" setup>
	import { computed, ref } from 'vue'
	import { expenditureLedgerApi, incomeLedgerApi, accountBookApi, assetsCategoriesApi, assetsApi, productCategoriesApi, incomeItemApi, expenditureItemApi } from "@/apis/apis"
	import { onShow, onLoad } from '@dcloudio/uni-app'
	import { userStore } from '@/store/user'
	import { getDate, unicodeToChar } from '@/utils/index'
	import { ImageLoader } from 'XrFrame/xrFrameSystem'
	const pageType = ref('add')
	onLoad((options : any) => {
		console.log('options', options);
		if (options.pageType) {
			pageType.value = options.pageType
			if (options.pageType === 'edit') {
				// 逐个属性更新保持响应式
				Object.keys(form.value).forEach(key => {
					if (userStore.CurrentExpenditur[key] !== undefined) {
						form.value[key] = userStore.CurrentExpenditur[key];
					}
				});
				selectedAccount.value = form.value.assetsName
				current.value = form.value.current
				if (current.value == 1) {
					form.value.expenditureAmount = userStore.CurrentExpenditur.incomeAmount
					form.value.expenditureItem = userStore.CurrentExpenditur.incomeItem
					form.value.expenditureItemId = userStore.CurrentExpenditur.incomeItemId
					form.value.expenditureTime = userStore.CurrentExpenditur.incomeTime
					form.value.expenditureType = userStore.CurrentExpenditur.incomeType
				}
				return
			}
		}
		getAccountBook()
	})
	// 选择账本
	const selectAccountBookRef = ref(null)

	const selectAccountBookFn = () => {
		if (selectAccountBookRef.value) selectAccountBookRef.value.selectAccountBook()
	}
	const selectAccountBookOk = (value : any) => {
		form.value.accountBookName = value.name
		form.value.accountBookId = value.id
	}

	const SysUser = JSON.parse(uni.getStorageSync('SysUser') || '{}')

	// 初始值工厂函数
	const getInitialForm = () => {
		console.log(getDate('time'));
		return {
			current: 0,
			accountBookName: '选择账本', //额外加的用来显示
			accountBookId: "",
			"accounting": "",
			"assetsId": "",
			assetsName: "",
			"deleted": "0",
			"deletedTime": "",
			id: null,
			"invoiceStatus": "",
			// "params": {},
			"quantity": "0",
			remarks: "填写备注",
			"unitPrice": "",
			userId: SysUser.id,
			// 以下是差异字段
			"expenditureAmount": "0",
			"expenditureItem": "",
			"expenditureItemId": "",
			"expenditureTime": getDate('time'),
			"expenditureType": "餐饮日常"
		}
		/* const incomeExtra = {
			"incomeAmount": "0",
			"incomeItem": "餐饮日常",
			"incomeItemId": "",
			"incomeTime": getDate(),
			"incomeType": "餐饮"
		}
		
		const expenditureExtra ={
			"expenditureAmount": "0",
			"expenditureItem": "餐饮日常",
			"expenditureItemId": "",
			"expenditureTime": "",
			"expenditureType": "餐饮",
		} */



	}
	// 重置函数
	const resetForm = () => {
		const { accountBookName, accountBookId } = form.value

		form.value = getInitialForm()

		form.value.accountBookName = accountBookName
		form.value.accountBookId = accountBookId
		keyboardType.value = 'expenditureAmount'

		panKeyBoardRef.value.cleanAll()

	}

	// 支出
	const form = ref(getInitialForm())
	const deleteFlag = ref(false)
	const deleteFn = () => {
		deleteFlag.value = true
	}
	const doDeleteFn = () => {
		alertDialogRef.value.open()
	}

	const selectBook = (e : any) => {
		e.selected = !e.selected
	}


	const dialogClose = () => {
		alertDialogRef.value.close()

	}
	const deleteOk = async () => {
		const ids = []
		categoryList.value.forEach((item : any) => item.selected && ids.push(item.id))
		let res : any = null

		if (current.value == 0) {
			res = await expenditureItemApi.deleteByIdsUsingDELETE_1({
				idList: ids.join(',')
			})
		} else {

			res = await incomeItemApi.deleteByIdsUsingDELETE_3({
				idList: ids.join(',')
			})
		}


		if (res.code === 200) {
			uni.showToast({ title: res.msg, icon: 'success' });
			deleteCancel()
			dialogClose()
			getCategory()

		}
	}
	const deleteCancel = () => {
		categoryList.value.forEach((item : any) => item.selected = false)
		deleteFlag.value = false
	}
	const messageText = `是否删除！`
	const alertDialogRef = ref(null)

	const changeSelectIcon = (e : any) => {
		if (deleteFlag.value) {
			e.selected = true
		} else {
			form.value.expenditureItem = e.categoryName
			form.value.expenditureItemId = e.id
		}
	}
	// 初始化请求账本
	const getAccountBook = async () => {
		const res : any = await accountBookApi.queryPageUsingPOST({ defaulted: '1' })
		if (res.data.records[0]) {
			form.value.accountBookName = res.data.records[0].name
			form.value.accountBookId = res.data.records[0].id
		}
	}

	const assets = ref([])

	// 初始化请求资产账户
	const getAssets = async () => {
		const res : any = await assetsApi.queryPageUsingPOST_2({ userId:/* userStore. */SysUser.id })
		assets.value = res.data.records
	}


	// 支出项目
	const getExpenditureItem = async () => {
		const res : any = await expenditureItemApi.queryPageUsingPOST_3({ pageSize: '999', userId: SysUser.id })

		res.data.records.forEach((item : any) => {
			categoryList.value.push({
				categoryName: item.expenditureName,
				iconName: item.iconName,
				id: item.id,
				selected: false
			})
		})
	}


	// 收入项目
	const getIncomeItem = async () => {
		const res : any = await incomeItemApi.queryPageUsingPOST_5({ pageSize: '999', userId: SysUser.id })
		// incomeItem.value = res.data.records
		res.data.records.forEach((item : any) => {
			categoryList.value.push({
				categoryName: item.incomeName,
				iconName: item.iconName,
				id: item.id,
				selected: false
			})
		})
	}

	const categoryList = ref([])

	const getCategory = async () => {
		categoryList.value = []

		if (current.value == 0) {
			getExpenditureItem()
		} else {
			getIncomeItem()
		}


	}
	onShow(() => {
		getAssets()
		getCategory()

	});

	const goTo = (type : string) => {
		if (type !== 'customCategory') return
		uni.navigateTo({
			url: `/pages/startKeepingAccounts/${type}/${type}?current=${current.value}`
		})
	}
	const goIndex = () => uni.navigateBack()
	const orc = () => {
		// 调用相机拍照
		uni.chooseImage({
			count: 1, // 最多选择数量
			sizeType: ['compressed'], // 压缩图
			sourceType: ['camera'], // 仅使用相机（改为 ['album'] 则为相册）
			success: (res) => {
				// 获取临时文件路径
				const tempFilePaths = res.tempFilePaths;
				console.log('照片路径:', tempFilePaths[0]);
			},
			fail: (err) => {
				console.error('调用失败:', err);
			}
		});
	}

	const current = ref(0)
	const items = ref(['支出', '收入'])


	const panKeyBoardRef = ref(null)

	const onClickItem = ({ currentIndex }) => {
		current.value = currentIndex
		resetForm()
		getCategory()
	}

	const value = ref(1)

	const range = ref([
		{ value: 1, text: "默认账本" },
	])

	const selectChange = (e : any) => {
		console.log(e);
	}

	/* const currentPicker = ref(0)
	const bindPickerChange = (e : any) => {
		currentPicker.value = e.detail.value
		form.value.expenditureItem = pickerArray.value[e.detail.value]
		form.value.expenditureItemId = expenditureItemList.value.find(item => item.expenditureName === pickerArray.value[e.detail.value]).id
	} */

	// 选择账户

	const popUpRef = ref(null)

	const selectedAccount = ref('')
	const selectAccountShow = () => {
		popUpRef.value.open()
	}
	const selectCancel = () => {
		assets.value.forEach((item : any) => item.selected = item.accountName === selectedAccount.value)
		popUpRef.value.close()
	}
	const selectOk = () => {
		selectedAccount.value = assets.value.find(item => item.selected)?.accountName
		form.value.assetsId = assets.value.find(item => item.selected)?.id
		form.value.assetsName = assets.value.find(item => item.selected)?.accountName

		selectCancel()
	}

	const selectAccount = (e : any) => {
		assets.value.forEach((item : any) => item.selected = false)
		e.selected = true
	}

	const startDate = getDate('day', 'start')
	const endDate = getDate('day', 'end')
	// uni-datetime-picker
	const bindMonthDateChange2 = (e : any) => {
		form.value.expenditureTime = e
	}
	// picker
	/* 	const bindMonthDateChange = (e : any) => {
			form.value.expenditureTime = e.detail.value as string
		} */

	// 填写备注
	const popUpRemarkRef = ref(null)
	const remarkShow = () => {
		popUpRemarkRef.value.open()
	}

	const input = (e : any) => {
		console.log(e);
	}

	// const popUpKeyRef = ref(null)
	const keyboardType = ref('expenditureAmount')

	const changeKeyboard = (type : string) => {

		keyboardType.value = type
		panKeyBoardRef.value.cleanAll()
		if (!['0', 0].includes(form.value[type])) panKeyBoardRef.value.setKeyboard(form.value[type])
	}
	// 键盘
	const onPanKeyboardChange = (e : any) => {
		console.log(e);
		form.value[keyboardType.value] = e.enterAmount
	}
	// 确定
	const onSubmit = async () => {
		let res : any = null
		const params : any = { ...form.value }

		if (!params.accountBookName || params.accountBookName === '选择账本') return uni.showToast({ title: '请选择账本', icon: 'error' })
		if (!params.assetsId) return uni.showToast({ title: '请选择账户', icon: 'error' })
		if (!params.expenditureItemId) return uni.showToast({ title: '请选择分类', icon: 'error' })
		if (!params.expenditureAmount) return uni.showToast({ title: '请输入金额', icon: 'error' })

		// 支出
		if (current.value == 0) {
			res = await expenditureLedgerApi[pageType.value === 'add' ? 'addUsingPOST_4' : 'updateUsingPUT_3'](params)
		} else {

			delete params.expenditureAmount
			delete params.expenditureItem
			delete params.expenditureItemId
			delete params.expenditureTime
			delete params.expenditureType

			params.incomeAmount = form.value.expenditureAmount
			params.incomeItem = form.value.expenditureItem
			params.incomeItemId = form.value.expenditureItemId
			params.incomeTime = form.value.expenditureTime
			params.incomeType = form.value.expenditureType

			res = await incomeLedgerApi[pageType.value === 'add' ? 'addUsingPOST_6' : 'updateUsingPUT_5'](params)
		}

		if (res.code === 200) {
			uni.showToast({ title: res.msg, icon: 'success' })
			uni.navigateBack()
		}

	}
</script>

<style lang="scss" scoped>
	$nav-height: 44px;



	.in-out {
		height: $nav-height;
		width: 100px;
		margin: 7px 0;
		line-height: $nav-height;

		.uni-padding-wrap {
			// width: 750rpx;
			padding: 0px 30px;
		}
	}


	.city {
		padding-top: 3px;
		margin-left: 60px;
		height: $nav-height;
		line-height: $nav-height;
		width: 100px;

	}


	.start-Keeeping-accounts {
		width: 90vw;
		height: calc(100vh - 222.69px - var(--status-bar-height));
		padding: 5px 20px 0;

		.dayly {
			padding: 30px;
			color: #fff;
			font-size: 25px;
			background-color: #FFAF5A;
			border-radius: 8px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.left {
				display: flex;
				align-items: center;
			}

			.text-1 {
				font-size: 20px;
				margin-left: 20px;
			}

			.amount {
				font-size: 20px;
			}
		}

		.scroll-Y {
			height: calc(100% - 100px - 100px - 35px - 104px);
			flex: 1;
			overflow: hidden;
		}

		.assets-content {
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;
			margin: 10px 0 10px;


		}



		.selet-section {
			padding-top: 20px;

			.selet-section-items {
				width: 48%;
				padding: 6px 6px 6px 16px;
				display: flex;
				align-items: center;

				.text-1 {
					width: 100px;
					font-size: 16px;
					margin-left: 5px;
				}


			}

			// 选择账户
			.select-account {
				background-color: #717171;
				border-radius: 0 37px 37px 0;
				color: #fff;
			}

			.select-account,
			.selet-time {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.item {
					display: flex;
					align-items: center;


				}
			}

			.selet-section-top,
			.selet-section-bottom {
				display: flex;
			}
		}
	}


	.accounts {
		padding: 10px;

		// 明细列表
		.list-item {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			padding: 10px;
			border: 1px solid #939597;
			margin-bottom: 10px;
			border-radius: 5px;
			position: relative;

			.list-item-content {
				display: flex;
				flex-direction: row;
				align-items: center;

				.list-item-content-view {
					margin-left: 10px;

					.remark {
						color: #939597;
					}
				}
			}

			.money {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;

				.select-icon {
					position: absolute;
					top: 2px;
					right: 2px;
				}
			}
		}


	}

	.popup-header {
		padding: 10px;
		display: flex;
		justify-content: space-between;
		padding-bottom: 10px;
	}

	.rmark {
		padding: 10px;
	}

	.key {
		// width: 90%;
		// position: fixed;
		// bottom: 20px;
		// left: 50%;
		// transform: translateX(-50%);
	}

	.assets-content-view {
		width: 20%;
		padding-bottom: 10px;
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;

		.select-icon {
			position: absolute;
			top: 2px;
			right: 2px;
		}
	}
</style>